#!/usr/bin/python
# Copyright @ 2010 Michael P. Reilly. All rights reserved.

from pyerector import *
from os.path import join, expanduser, normpath
from os import getcwd, getpid

PWD = normpath(getcwd())
VarDir = join(PWD, 'var')
DsDir = join(VarDir, 'ds')
HistDir = join(VarDir, 'history')

Port = 8916

class DevAppServer(Spawn):
    cmd = (
        #'python2.5 ' +
        expanduser(join('~', 'bin', 'dev_appserver.py')) +
        ' --port=%s' % Port +
        ' --datastore_path=%s' % DsDir +
        ' --history_path=%s' % HistDir +
        ' ' + PWD
    )

class AppCfgUpdate(Spawn):
    cmd = (
        'python2.5' +
        ' ' + join('/', 'opt', 'google_appengine', 'current', 'appcfg.py') +
        ' --passin' +
        ' --email=arcege@gmail.com' +
        ' update' +
        ' ' + join(PWD, 'dist')
    )
    infile = expanduser(join('~', '.gae_password'))

class CaptureAppCfgCache(Task):
    files = (expanduser(join('~', '.appcfg_*')),)
    def run(self):
        global CaptureCache
        CaptureCache = expanduser(join('~', '.capturecache.%d' % getpid()))
        Mkdir()(CaptureCache)
        Copy()(*self.files, dest=CaptureCache)
        Remove()(*self.files)
class RestoreAppCfgCache(Task):
    def run(self):
        global CaptureCache
        Copy()(join(CaptureCache, '.appcfg_*'), dest=expanduser('~'))
        Remove()(CaptureCache)

class CleanAppCfgCache(Remove):
    files = (expanduser(join('~', '.appcfg_*')),)

class Update(Target):
    "Push distribution to appengine server(s)"
    dependencies = ("Dist",)
    tasks = ("CaptureAppCfgCache", "AppCfgUpdate", "RestoreAppCfgCache")

class Start(Target):
    "Start dev appserver"
    dependencies = ("InitDirs",)
    tasks = ("DevAppServer",)

InitDirs.files = ("dist", VarDir)

class Clean(Target):
    def run(self):
        from os import listdir
        from os.path import isdir
        dirs = [ PWD ]
        while dirs:
            dir = dirs.pop()
            for fname in listdir(dir):
                if fname.endswith('.pyc'):
                    Remove()(join(dir, fname))
                elif isdir(join(dir, fname)):
                    dirs.append(join(dir, fname))
        Remove()("dist")

class Dist(Target):
    def run(self):
        # copy the code without the .svn
        CopyTree()('templates', 'dist/templates')
        CopyTree()('static', 'dist/static')
        CopyTree()('kcapp', 'dist/kcapp')
        Copy()(
            'admin.py',
            'help.py',
            'index.py',
            'keycustodian.py',
            'relinfo.py',
            'userpref.py',
            'xmlhttp.py',
            'dist'
        )
        Copy()(
            'app.yaml',
            'index.yaml',
            'dist'
        )

class Realclean(Target):
    "Remove local datastore"
    dependencies = ("Clean",)
    def run(self):
        Remove()( VarDir )

if __name__ == '__main__':
    pymain()
